package com.tangkun.environment.fragment.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tangkun.environment.R;
import com.tangkun.environment.adapter.FragmentAdapter;
import com.tangkun.environment.adapter.XinwenTypeAdapter;
import com.tangkun.environment.application.Session;
import com.tangkun.environment.entity.xinwen.TypeReturn;
import com.tangkun.environment.fragment.BaseFragment;
import com.tangkun.environment.fragment.news.XinWenFragment;
import com.tangkun.environment.fragment.news.ZiXunFragment;
import com.tangkun.environment.network.GlobalUrl;
import com.tangkun.environment.network.MySubscribe;
import com.tangkun.environment.rx.RxFragmentHelper;
import com.tangkun.environment.utils.LogUtils;
import com.tangkun.environment.view.CircleImageView;
import com.tangkun.environment.view.CustomPopWindow;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.CropCircleTransformation;

/**
 * 新闻Fragment
 */

public class Main3Fragment extends BaseFragment {
    @BindView(R.id.rl_main_tab)
    RelativeLayout rlMainTab;
    @BindView(R.id.rb_health_butler_jinxingzhong)
    RadioButton rbHealthButlerJinxingzhong;
    @BindView(R.id.rb_health_butler_yiwancheng)
    RadioButton rbHealthButlerYiwancheng;
    @BindView(R.id.rg_health_butler)
    RadioGroup rgHealthButler;
    @BindView(R.id.viewpager_health_butler)
    ViewPager mViewPager;
    @BindView(R.id.civ_main_photo)
    CircleImageView civMainPhoto;
    @BindView(R.id.tv_main_type)
    TextView tvMainType;
    @BindView(R.id.rl_main_type)
    RelativeLayout rlMainType;

    /*** Fragment+ViewPager ***/
    private ArrayList<Fragment> mFragmentList;
    private FragmentAdapter mFragmentAdapter;
    /**
     * Fragment选中项,0:新闻 1:咨询
     */
    private int mPosition = 0;

    /**
     * popupwindow
     */
    private CustomPopWindow mPopupWindow;

    /**
     * 新闻类别
     */
    private List<TypeReturn.DataBean> newsTypeDataList = new ArrayList<TypeReturn.DataBean>();
    /**
     * 咨询分类
     */
    private List<TypeReturn.DataBean> questionTypeDataList = new ArrayList<TypeReturn.DataBean>();
    /**
     * 数据源
     */
    List<TypeReturn.DataBean> dataList = new ArrayList<TypeReturn.DataBean>();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_main3, container, false);
        ButterKnife.bind(this, view);
        initView();
        initFragment();
        initListener();
        initData();
        //新闻类别
        queryType("news-type");
        //咨询分类
        queryType("question-type");
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    private void initView() {

    }

    private void initData() {
        //顶部左上角头像
        Glide.with(getActivity())
                .load(GlobalUrl.IMG_URL + Session.getInstance().getUserHeadPicture())
                .bitmapTransform(new CropCircleTransformation(getActivity()))
                .placeholder(R.mipmap.ic_wrong_head)
                .dontAnimate()
                .into(civMainPhoto);
    }

    private void initFragment() {
        mFragmentList = new ArrayList<Fragment>();
        Fragment contactListFragment1 = new XinWenFragment();
        Fragment contactListFragment2 = new ZiXunFragment();
        mFragmentList.add(contactListFragment1);
        mFragmentList.add(contactListFragment2);
        // tangkun:嵌套Fragment设置PageAdapter时要使用getChildFragmentManager,而不能使用getActivity().getSupportFragmentManager()
        mFragmentAdapter = new FragmentAdapter(getChildFragmentManager(), mFragmentList);
        mViewPager.setAdapter(mFragmentAdapter);
        mFragmentAdapter.setFragments(mFragmentList);
        mViewPager.setOffscreenPageLimit(2);
        mViewPager.setOnPageChangeListener(new MyOnPageChangeListener());
        mViewPager.setCurrentItem(mPosition);
    }

    private void initListener() {
        //消息通讯录切换
        rgHealthButler.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                switch (i) {
                    case R.id.rb_health_butler_jinxingzhong:
                        mViewPager.setCurrentItem(0, true);
                        break;
                    case R.id.rb_health_butler_yiwancheng:
                        mViewPager.setCurrentItem(1, true);
                        break;

                }
            }
        });
    }

    @OnClick({R.id.civ_main_photo, R.id.rl_main_type})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.civ_main_photo:
                EventBus.getDefault().post(true, "MainActivity.openDrawer");//发出通知给MainActivity，打开左抽屉
                break;
            case R.id.rl_main_type://新闻分类
                //只有新闻才显示分类
                if (mPosition == 0) {
                    backgroundAlpha(0.5f);
                    View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_xinwenfenlei, null);
                    //初始化历史选中项
                    initPopupWindowView(contentView);
                    //创建并显示popWindow
                    mPopupWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                            .setView(contentView)
                            .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                                @Override
                                public void onDismiss() {
                                    backgroundAlpha(1f);
                                }
                            })
                            .create()
                            .showAsDropDown(rlMainType);
                }
                break;
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getActivity().getWindow().setAttributes(lp);
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }


    /**
     * 初始化历史选中项
     *
     * @param contentView
     */
    private void initPopupWindowView(final View contentView) {
        switch (mPosition) {
            case 0://0:新闻
                dataList = newsTypeDataList;
                break;//1:咨询
            case 1:
                dataList = questionTypeDataList;
                break;

        }
        final XinwenTypeAdapter adapter = new XinwenTypeAdapter(getActivity(), dataList);
        ListView listView = (ListView) contentView.findViewById(R.id.listview);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                for (int i = 0; i < dataList.size(); i++) {
                    dataList.get(i).isSelected = false;
                }
                dataList.get(position).isSelected = true;
                //更改筛选文字
                tvMainType.setText(dataList.get(position).val + "");
                //类别的ID
                String ids = dataList.get(position).ids;
                adapter.notifyDataSetChanged();
                mPopupWindow.dissmiss();
                //发出通知，刷新新闻中的新闻列表
                Intent intent = new Intent();
                intent.putExtra("type", ids);
                EventBus.getDefault().post(intent, "XinWenFragment.refreshNews");
            }
        });

    }


    /**
     * ViewPager监听事件
     */
    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageSelected(final int position) {
            mPosition = position;
            if (position == 0) {
                rgHealthButler.check(R.id.rb_health_butler_jinxingzhong);
                rlMainType.setVisibility(View.VISIBLE);
            } else {
                rgHealthButler.check(R.id.rb_health_butler_yiwancheng);
                rlMainType.setVisibility(View.GONE);
            }
        }

        @Override
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels) {
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    /**
     * 获取首页轮播图
     *
     * @param numbers 新闻类别：news-type；咨询分类：question-type
     */
    private void queryType(final String numbers) {
        fromNetwork.queryType(numbers).compose(new RxFragmentHelper<TypeReturn>().ioMain(getActivity(), Main3Fragment.this, false))
                .subscribe(new MySubscribe<TypeReturn>(getActivity(), false) {
                    @Override
                    protected void success(TypeReturn resultBean) {
                        if (resultBean.data != null) {
                            switch (numbers) {
                                case "news-type"://新闻类别
                                    newsTypeDataList.clear();
                                    newsTypeDataList.addAll(resultBean.data);
                                    //第一位增加一个全部
                                    TypeReturn.DataBean dataBean = new TypeReturn.DataBean();
                                    dataBean.ids = "";
                                    dataBean.val = "全部";
                                    dataBean.isSelected = true;
                                    newsTypeDataList.add(0, dataBean);
                                    break;
                                case "question-type"://咨询分类
                                    questionTypeDataList.clear();
                                    questionTypeDataList.addAll(resultBean.data);
                                    break;
                            }
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage + "");
                    }
                });
    }
}
